﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.ServiceModel.Web;
using System.Threading;
using Microsoft.Rtc.Collaboration.Samples.HTMLPresenceControls.Service.Common;

namespace Microsoft.Rtc.Collaboration.Samples.HTMLPresenceControls.Service
{
    public class Global : System.Web.HttpApplication
    {
        WebServiceHost _presenceQueryServiceHost;
        public static UcPresenceCache PresenceCache;

        void Application_Start(object sender, EventArgs e)
        {
             StartPresenceQueryService();
        }

        private void StartPresenceQueryService()
        {
            Helper.Logger.Info("PresenceQueryService starting up");
            UcmaHelper.GetInstance().Start(
                ConfigurationManager.AppSettings["ApplicationName"],
                ConfigurationManager.AppSettings["ApplicationId"]);
            IPresenceProvider provider = new UcPresenceProvider(UcmaHelper.GetInstance().ApplicationEndpoint);
            if (provider.Start())
            {
                PresenceCache = new UcPresenceCache(provider);
                PresenceQueryService.Service queryService = new PresenceQueryService.Service(PresenceCache);
                _presenceQueryServiceHost = new WebServiceHost(queryService);
                _presenceQueryServiceHost.Open();
                Helper.Logger.Info("PresenceQueryService started successfully");
            }
            else
            {
                Helper.Logger.Info("PresenceQueryService failed to start");
            }
        }
      

        void Application_End(object sender, EventArgs e)
        {
            StopPresenceQueryService();
        }

        private void StopPresenceQueryService()
        {
            UcmaHelper.GetInstance().Stop();
            Helper.Logger.Info("PresenceQueryService stopped successfully");
        }

        void Application_Error(object sender, EventArgs e)
        {
            Exception ex = Server.GetLastError();
            Helper.Logger.Error("Unhandled exception {0}", ex);
            Server.ClearError();
        }

        void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started

        }

        void Session_End(object sender, EventArgs e)
        {
            // Code that runs when a session ends. 
            // Note: The Session_End event is raised only when the sessionstate mode
            // is set to InProc in the Web.config file. If session mode is set to StateServer 
            // or SQLServer, the event is not raised.

        }

    }
}
